import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom';
import { Menu } from 'antd';

import { configRoutes } from '@/router';
import { getConfigMenuArr, getCurrentMenuKeyArr } from '@/utils/utils';

const { SubMenu, Item: MenuItem } = Menu;

const MyMenu: React.FunctionComponent<any> = (props: any) => {

  const navigate = useNavigate();
  const location = useLocation();
  const { pathname } = location;
  const { mode, theme, overflowedIndicator, style, level, isDepth, iconMenuItem } = props;
  
  const [currentKeyArr, setCurrentKeyArr] = useState<Array<string>>([]);
  const [menuData, setMenuData] = useState<any>([]);

  useEffect(() => {
    // 菜单配置数据
    const actMenuData = getConfigMenuArr(configRoutes, level, isDepth, pathname);
    const currentKeyArr = getCurrentMenuKeyArr(pathname);
    setMenuData(actMenuData);
    setCurrentKeyArr(currentKeyArr);
  }, [level, isDepth, pathname]);

  const handleClick = (e: any) => {
    setCurrentKeyArr([e.key]);
    navigate(e.key);
  };

  // 获取图标
  const IconMenuItem = iconMenuItem && iconMenuItem.type;

  return (
    <Menu onClick={handleClick} selectedKeys={[...currentKeyArr]} theme={theme} mode={mode} overflowedIndicator={overflowedIndicator} style={style} >
      {iconMenuItem && iconMenuItem.type && <IconMenuItem />}
      {!isDepth && menuData.map((item: any, index: number) => {
        return (
          <MenuItem key={item.actPath} icon={item?.iocn}>
            {item.name}
          </MenuItem>
        );
      })}
      {isDepth && menuData.map((item: any) => {
        const { children } = item;
        if(children && children.length) {
          const actInlineMenuData = [item, ...children];
          return (
            <SubMenu key={item.actPath} icon={item?.iocn} title={item.name}>
              {actInlineMenuData.map((cItem: any) => {
                return (
                  <MenuItem key={cItem.actPath} icon={cItem?.iocn}>
                    {cItem.name}
                  </MenuItem>
                );
              })}
            </SubMenu>
          )
        }else{
          return (
            <MenuItem key={item.actPath} icon={item?.iocn}>
              {item.name}
            </MenuItem>
          );
        }
      })}
    </Menu>
  );
}
export default MyMenu;